package com.stars.easyms.schedule.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
 * 
 * @author guoguifang
 */
public class ApplicationContextHolder {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationContextHolder.class);

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (ApplicationContextHolder.applicationContext == null) {
            ApplicationContextHolder.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String beanId) {
        if (applicationContext != null && StringUtils.isNotBlank(beanId)) {
            try {
                return applicationContext.getBean(beanId);
            } catch (BeansException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bean failed to get beanId '{}'!", beanId);
                }
            }
        }
        return null;
    }

    public static Object getBean(Class beanClass) {
        if (applicationContext != null && beanClass != null) {
            try {
                return applicationContext.getBean(beanClass);
            } catch (BeansException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bean failed to get bean class '{}'!", beanClass.getName());
                }
            }
        }
        return null;
    }

}
